﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Web;
using System.Web.SessionState;
using Donal.Xms.Web.UI;
using Donal.Xms.Common;
using System.Drawing.Imaging;
using System.IO;
using ThoughtWorks.QRCode.Codec;
using Donal.Xms.Web.qianyi.manager;
using System.Reflection;
using System.Web.Services.Description;

namespace Donal.Xms.Web.tools
{
    /// <summary>
    /// submit_ajax 的摘要说明
    /// </summary>
    public class submit_ajax : IHttpHandler, IRequiresSessionState
    {
        Model.sysconfig sysConfig = new BLL.sysconfig().loadConfig();
        Model.userconfig userConfig = new BLL.userconfig().loadConfig();
        UserPage userPage = new UserPage();

        public void ProcessRequest(HttpContext context)
        {
            //取得处事类型
            string action = DTRequest.GetQueryString("action");

            if (action.LastIndexOf("_") > 0)
            {
                action = action.Substring(0, action.LastIndexOf("_"));
            }

            switch (action)
            {
                case "comment_add": //提交评论
                    comment_add(context);
                    break;
                case "comment_list": //评论列表
                    comment_list(context);
                    break;
                case "validate_username": //验证用户名
                    validate_username(context);
                    break;
                case "user_check_login": //检查用户是否登录
                    user_check_login(context);
                    break;
                case "user_verify_smscode": //发送手机短信验证码
                    user_verify_smscode(context);
                    break;
                case "user_verify_email": //发送注册验证邮件
                    user_verify_email(context);
                    break;
                case "user_info_edit": //修改用户资料
                    user_info_edit(context);
                    break;
                case "user_avatar_crop": //确认裁剪用户头像
                    user_avatar_crop(context);
                    break;
                case "user_password_edit": //修改密码
                    user_password_edit(context);
                    break;
                case "user_getpassword": //用户取回密码
                    user_getpassword(context);
                    break;
                case "user_repassword": //用户重设密码
                    user_repassword(context);
                    break;
                case "user_invite_code": //申请邀请码
                    user_invite_code(context);
                    break;
                case "user_amount_recharge": //用户在线充值
                    user_amount_recharge(context);
                    break;
                case "user_message_add": //发布站内短消息
                    user_message_add(context);
                    break;
                case "user_address_edit": //编辑用户收货地址
                    user_address_edit(context);
                    break;
                case "user_point_delete": //删除用户积分明细
                    user_point_delete(context);
                    break;
                case "user_amount_delete": //删除用户收支明细
                    user_amount_delete(context);
                    break;
                case "user_recharge_delete": //删除用户充值记录
                    user_recharge_delete(context);
                    break;
                case "user_message_delete": //删除短信息
                    user_message_delete(context);
                    break;
                case "get_article_goods_info": //商品信息
                    get_article_goods_info(context);
                    break;
                case "view_article_click": //统计及输出阅读次数
                    view_article_click(context);
                    break;
                case "view_comment_count": //输出评论总数
                    view_comment_count(context);
                    break;
                case "view_attach_count": //输出附件下载总数
                    view_attach_count(context);
                    break;

                case "submit_like": //提交喜欢操作
                    submit_like(context);
                    break;
                case "get_QRcode": //获取QRcode
                    get_QRcode(context);
                    break;
                case "isExistMobile":
                    this.isExistMobile(context);
                    return;
                case "user_logout": //用户退出
                    user_logout(context);
                    break;
                case "wxConfig"://获取微信配置信息
                    wxConfig(context);
                    break;
                case "wxConfigClear"://清空微信配置信息
                    wxConfigClear(context);
                    break;
                case "getvideo"://获取视频
                    getvideo(context);
                    break;
                case "CreateUploadVideoResponse"://获取视频上传地址和凭证
                    CreateUploadVideoResponse(context);
                    break;
                case "user_login": //用户登录 AllSure
                    user_login(context);
                    break;
                case "user_register": //用户注册 AllSure
                    user_register(context);
                    break;
                case "view_cart_count": //输出当前购物车总数 AllSure
                    view_cart_count(context);
                    break;
                case "add_cart": //添加商品到购物车OK AllSure
                    add_cart(context);
                    break;
                case "set_cart_quantity": //设置购物车数量OK AllSure
                    set_cart_quantity(context);
                    break;
                case "del_cart_goods": //删除购物车中的商品OK AllSure
                    del_cart_goods(context);
                    break;
                case "confirm": //确认订单OK AllSure
                    confirm(context);
                    break;
                case "submitOrder": //提交订单OK AllSure
                    submitOrder(context);
                    break;
            }
        }

        #region AllSure

        #region  AllSure 提交订单OK===============================
        private void submitOrder(HttpContext context)
        {
            if (context.Session[DTKeys.SESSION_ORDER_CONFIRM_INDEX] == null)
            {
                context.Response.Write("{\"status\": 2, \"msg\": \"提交无效\"}");
                return;
            }

            int submitIndex = Utils.ObjToInt(context.Session[DTKeys.SESSION_ORDER_CONFIRM_INDEX], 1);

            if (submitIndex != 0)
            {
                context.Response.Write("{\"status\": 3, \"msg\": \"提交无效\"}");
                return;
            }
            else
            {
                context.Session[DTKeys.SESSION_ORDER_CONFIRM_INDEX] = 1;
            }

            System.Threading.Thread.Sleep(5000);
            ResponseWrite(context, 0, "这是测试！");
            return;

            if (userPage.IsUserLogin())
            {
                Model.users user = userPage.GetUserInfo();

                //1整单发货 2分批发货 其它：入库订单
                int delivery = DTRequest.GetFormInt("delivery");
                int address = DTRequest.GetFormInt("address");
                string remark = DTRequest.GetFormString("remark");
                DataSet dsGoods = new DataSet();

                if (context.Session[DTKeys.SESSION_ORDER_SUBMIT] != null)
                {
                    try
                    {
                        Model.user_addr_book addressModel = new Model.user_addr_book();

                        if (address > 0)
                        {
                            addressModel = new BLL.user_addr_book().GetModel(address);
                            if (addressModel == null)
                            {
                                ResponseWrite(context, 0, "收货地址已变更，请重新选择！");
                                return;
                            }
                        }

                        dsGoods = (DataSet)context.Session[DTKeys.SESSION_ORDER_SUBMIT];

                        if (!Utils.CheckDataSet(dsGoods))
                        {
                            ResponseWrite(context, 0, "订单不存在或已过期！");
                            return;
                        }

                        List<Model.order_goods> order_Goods = new List<Model.order_goods>();
                        decimal amount = 0;
                        int standard = 0;

                        foreach (DataRow dr in dsGoods.Tables[0].Rows)
                        {
                            amount += Utils.ObjToDecimal(dr["amount"], 0);

                            order_Goods.Add(new Model.order_goods()
                            {
                                abstracts = dr["abstracts"].ToString(),
                                add_time = DateTime.Now,
                                category_title = dr["category_title"].ToString(),
                                contents = dr["contents"].ToString(),
                                discount_price = Utils.ObjToDecimal(dr["discount_price"].ToString(), 0),
                                discount_remark = dr["discount_remark"].ToString(),
                                erp_goods_no = dr["erp_goods_no"].ToString(),
                                fields = dr["fields"].ToString(),
                                goods_title = dr["title"].ToString(),
                                img_url = dr["img_url"].ToString(),
                                link_url = dr["link_url"].ToString(),
                                product_title = dr["product_title"].ToString(),
                                quantity = Utils.ObjToInt(dr["quantity"].ToString()),
                                sell_price = Utils.ObjToDecimal(dr["sell_price"].ToString(), 0),
                                sub_title = dr["sub_title"].ToString(),
                                order_express_id = 0
                            });

                            if (standard == 0 && dr["standard"].ToString() == "1")
                            {
                                standard = 1;
                            }
                        }

                        string orderNo = Utils.GetOrderNumber();//订单号

                        Model.orders order = new Model.orders()
                        {
                            order_no = orderNo,//订单号
                            order_type = 0,//标准与非标
                            over_time = DateTime.Now.AddDays(sysConfig.is_sms),//订单过期时间
                            delivery = delivery,//发货方式

                            express_type = address == 0 ? 0 : 1,//自提与快递
                            express_status = 0,//发货状态 0未发货 1已发货 2部分发货
                            accepte_mobile = (address == 0 ? user.mobile : addressModel.mobile),
                            accepte_name = (address == 0 ? user.nick_name : addressModel.accept_name),
                            accept_address = (address == 0 ? user.address : addressModel.address),
                            area_address = (address == 0 ? user.area : addressModel.area),

                            company_group = new BLL.user_groups().GetTitle(user.company.group_id),
                            company_id = user.parent_id,
                            company_title = user.company.companyName,
                            company_type = user.company.user_type == 0 ? "普通" : "月结",

                            goods_amount = amount,//商品总额
                            order_amount = 0,//订单金额 = 商品总额 - 优惠卷金额
                            payment_amount = 0,//已支付金额
                            coupons_amount = 0,//优惠卷金额
                            coupons_remark = "",//优惠卷说明

                            order_standard = standard,//标准与非标
                            order_confirm = 0,//确认状态
                            confirm_time = null,//确认时间
                            deposit = 0,//订金
                            deposit_need = 0,//是否需要订金
                            deposit_paymented = 0,//订金是否已交
                            deposit_paymented_id = 0,//订金支付ID                                                                                   

                            payment = "",//支付试
                            payment_status = 0,//订单支付状态 0 未支付，1已支付
                            paymented_id = 0,//订单支付ID
                            payment_time = null,
                            remark = remark,
                            status = delivery == 1 ? 1 : delivery == 2 ? 6 : 0,//订单状态
                            user_name = user.user_name,

                            order_goods = order_Goods,//订单中的商品
                            orders_express = new List<Model.orders_express>(),//发货列表
                            orders_invoice = new List<Model.orders_invoice>(),
                            add_time = DateTime.Now,

                            is_del = 0
                        };

                        BLL.orders bll = new BLL.orders();

                        if (bll.Add(order) > 0)
                        {
                            ResponseWrite(context, 1, orderNo);
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        Utils.WriteLogs("订单", "异常", ex.Message + "：" + ex.StackTrace);
                        ResponseWrite(context, 0, "发生异常，请联系管理员！");
                        return;
                    }
                }
                else
                {
                    ResponseWrite(context, 0, "订单不存在或已过期！");
                    return;
                }

            }
            else
            {
                ResponseWrite(context, 0, "您还没有登录！");
                return;
            }
        }

        private void ResponseWrite(HttpContext context, int status, string message)
        {
            context.Session[DTKeys.SESSION_ORDER_CONFIRM_INDEX] = 0;
            context.Response.Write("{\"status\": " + status + ", \"msg\": \"" + message + "\"}");
            return;
        }

        #endregion

        #region  AllSure 确认订单OK===============================
        private void confirm(HttpContext context)
        {
            if (userPage.IsUserLogin())
            {
                string gs = DTRequest.GetFormString("gs");

                if (!gs.EndsWith(","))
                {
                    context.Response.Write("{\"status\": 0, \"msg\": \"参数有误[001]！\"}");
                    return;
                }

                gs = gs.Substring(0, gs.Length - 1);

                string[] gcs = gs.Split(',');

                if (gcs.Length > 0)
                {
                    context.Session[DTKeys.SESSION_ORDER_CONFIRM] = DESEncrypt.Encrypt(DateTime.Now.ToString("mmss") + "_" + gs);
                    context.Response.Write("{\"status\": 1, \"msg\": \"操作成功！\"}");
                    return;
                }
                else
                {
                    context.Response.Write("{\"status\": 0, \"msg\": \"参数有误[002]！\"}");
                    return;
                }

            }
            else
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"您还没有登录！\"}");
                return;
            }
        }
        #endregion

        #region  AllSure 删除购物车中的商品OK===============================
        private void del_cart_goods(HttpContext context)
        {
            if (userPage.IsUserLogin())
            {
                int id = DTRequest.GetFormInt("i");
                int goods_id = DTRequest.GetFormInt("g");
                int quantity = DTRequest.GetFormInt("q");

                BLL.cart bll = new BLL.cart();

                Model.cart cart = bll.GetModel(id);

                if (cart != null && cart.goods_id == goods_id && cart.user_id == userPage.GetUserInfo().parent_id)
                {
                    cart.quantity = quantity;
                    context.Response.Write("{\"status\": 1, \"msg\": \"" + bll.Delete(id) + "\"}");
                    return;
                }

                context.Response.Write("{\"status\": 0, \"msg\": \"温馨提示：操作失败！\"}");
                return;
            }
            else
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"温馨提示：用户未登录！\"}");
                return;
            }

        }
        #endregion

        #region  AllSure 设置购物车数量OK===============================
        private void set_cart_quantity(HttpContext context)
        {
            if (userPage.IsUserLogin())
            {
                int id = DTRequest.GetFormInt("i");
                int goods_id = DTRequest.GetFormInt("g");
                int quantity = DTRequest.GetFormInt("q");

                BLL.cart bll = new BLL.cart();

                Model.cart cart = bll.GetModel(id);

                if (cart != null && cart.goods_id == goods_id && cart.user_id == userPage.GetUserInfo().parent_id)
                {
                    cart.quantity = quantity;
                    context.Response.Write("{\"status\": 1, \"msg\": " + bll.Update(cart) + "}");
                    return;
                }

                context.Response.Write("{\"status\": 0, \"msg\": \"温馨提示：操作失败！\"}");
                return;
            }
            else
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"温馨提示：用户未登录！\"}");
                return;
            }

        }
        #endregion

        #region  AllSure 添加商品到购物车OK===============================
        private void add_cart(HttpContext context)
        {
            if (userPage.IsUserLogin())
            {
                BLL.cart bll = new BLL.cart();

                string gc = DTRequest.GetFormString("gc");

                if (!gc.EndsWith(","))
                {
                    context.Response.Write("{\"status\": 0, \"msg\": \"参数有误[001]！\"}");
                    return;
                }

                gc = gc.Substring(0, gc.Length - 1);

                string[] gcs = gc.Split(',');

                if (gcs.Length > 0)
                {
                    foreach (string s in gcs)
                    {
                        string[] gs = s.Split('-');
                        if (gs.Length == 2 && Utils.isNumber(gs[0]) && Utils.isNumber(gs[1]) && Utils.ObjToInt(gs[1]) > 0)
                        {
                            if (new BLL.products_goods().Exists(Utils.ObjToInt(gs[0])))
                            {
                                Model.cart cart = bll.GetModel(userPage.GetUserInfo().parent_id, Utils.ObjToInt(gs[0]));

                                if (cart != null)
                                {
                                    cart.quantity += Utils.ObjToInt(gs[1]);
                                    bll.Update(cart);
                                }
                                else
                                {
                                    bll.Add(new Model.cart
                                    {
                                        add_time = DateTime.Now,
                                        goods_id = Utils.ObjToInt(gs[0]),
                                        quantity = Utils.ObjToInt(gs[1]),
                                        user_id = userPage.GetUserInfo().parent_id
                                    });
                                }
                            }
                            else
                            {
                                context.Response.Write("{\"status\": 0, \"msg\": \"产品已下架！\"}");
                                return;
                            }
                        }
                        else
                        {
                            context.Response.Write("{\"status\": 0, \"msg\": \"参数有误[002]！\"}");
                            return;
                        }
                    }

                    context.Response.Write("{\"status\": 1, \"msg\": \"添加成功！\"}");
                    return;
                }
                else
                {
                    context.Response.Write("{\"status\": 0, \"msg\": \"参数有误[003]！\"}");
                    return;
                }

            }
            else
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"您还没有登录！\"}");
                return;
            }
        }
        #endregion

        #region  AllSure 输出购物车总数OK===============================
        private void view_cart_count(HttpContext context)
        {
            if (userPage.IsUserLogin())
            {
                context.Response.Write("{\"status\": 1, \"count\": " + new BLL.cart().GetCount(userPage.GetUserInfo().parent_id) + "}");
                return;
            }
            else
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"温馨提示：用户未登录！\"}");
                return;
            }
        }
        #endregion

        #region AllSure 用户登录OK=====================================
        private void user_login(HttpContext context)
        {
            string username = DTRequest.GetFormString("mobile");
            string password = DTRequest.GetFormString("password");
            string code = DTRequest.GetFormString("code");

            //校检验证码
            string result1 = verify_code(context, code);
            if (result1 != "success")
            {
                context.Response.Write(result1);
                return;
            }

            //检查用户名密码
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"温馨提示：请输入手机号或密码！\"}");
                return;
            }

            BLL.users bll = new BLL.users();
            Model.users model = bll.GetModel(username, password, userConfig.emaillogin, userConfig.mobilelogin, true);
            if (model == null)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"错误提示：手机号或密码错误，请重试！\"}");
                return;
            }
            //检查用户是否通过验证
            if (model.status == 1) //待验证
            {
                if (userConfig.regverify == 1)
                {
                    context.Response.Write("{\"status\":0, \"msg\":\"错误提示：会员尚未通过验证！\"}");
                    return;
                }
                else
                {
                    context.Response.Write("{\"status\":0, \"msg\":\"错误提示：会员尚未通过验证！\"}");
                    return;
                }
            }
            else if (model.status == 2) //待审核
            {
                context.Response.Write("{\"status\":0, \"msg\":\"错误提示：会员尚未通过审核！\"}");
                return;
            }

            context.Session[DTKeys.SESSION_USER_INFO] = model;
            context.Session.Timeout = 45;
            //记住登录状态下次自动登录
            Utils.WriteCookie(DTKeys.COOKIE_USER_NAME_REMEMBER, "Donal.Xms.UserName",
                DESEncrypt.Encrypt(DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "_" + DESEncrypt.Encrypt(model.user_name)), 43200);
            Utils.WriteCookie(DTKeys.COOKIE_USER_PWD_REMEMBER, "Donal.Xms.PassWord",
                    DESEncrypt.Encrypt(DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "_" + model.password), 43200);

            //写入登录日志
            new BLL.user_login_log().Add(model.id, model.user_name, "会员登录");
            //返回URL
            context.Response.Write("{\"status\":1, \"msg\":\"会员登录成功！\"}");
            return;
        }
        #endregion

        #region AllSure 用户注册OK=====================================
        private void user_register(HttpContext context)
        {
            string code = DTRequest.GetFormString("sms").Trim();
            string mobile = Utils.ToHtml(DTRequest.GetFormString("mobile").Trim());

            //检查是否开启会员功能
            if (sysConfig.memberstatus == 0)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，会员功能已关闭，无法注册！\"}");
                return;
            }
            if (userConfig.regstatus == 0)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，系统暂不允许注册新用户！\"}");
                return;
            }
            //如果开启手机注册则要验证手机
            if (string.IsNullOrEmpty(mobile))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"错误：手机号码不能为空！\"}");
                return;
            }

            //验证手机验证码
            string result2 = verify_sms_code(context, code);
            if (result2 != "success")
            {
                context.Response.Write(result2);
                return;
            }

            //检查用户名
            BLL.users bll = new BLL.users();

            Model.users model = bll.GetModel(mobile);
            if (model == null)
            {
                //检查默认组别是否存在
                Model.user_groups modelGroup = new BLL.user_groups().GetDefault();
                if (modelGroup == null)
                {
                    context.Response.Write("{\"status\":0, \"msg\":\"用户尚未分组，请联系网站管理员！\"}");
                    return;
                }
                model = new Model.users();
                model.parent_id = 0;
                model.group_id = modelGroup.id;
                model.user_name = mobile;
                model.salt = Utils.GetCheckCode(6); //获得6位的salt加密字符串
                model.password = DESEncrypt.Encrypt(mobile, model.salt);
                model.mobile = mobile;
                model.add_time = DateTime.Now;
                model.status = 0; //正常

                //开始写入数据库
                model.id = bll.Add(model);
                if (model.id < 1)
                {
                    context.Response.Write("{\"status\":0, \"msg\":\"系统故障，请联系网站管理员！\"}");
                    return;
                }
            }

            context.Session[DTKeys.SESSION_USER_INFO] = model;
            context.Session.Timeout = 45;

            //记住登录状态下次自动登录
            Utils.WriteCookie(DTKeys.COOKIE_USER_NAME_REMEMBER, "Donal.Xms.UserName",
                DESEncrypt.Encrypt(DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "_" + DESEncrypt.Encrypt(model.user_name)), 43200);
            Utils.WriteCookie(DTKeys.COOKIE_USER_PWD_REMEMBER, "Donal.Xms.PassWord",
                    DESEncrypt.Encrypt(DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "_" + model.password), 43200);

            //写入登录日志
            new BLL.user_login_log().Add(model.id, model.user_name, "会员登录");

            context.Response.Write("{\"status\":1, \"msg\":\"登录成功！\"}");
            return;

        }
        #endregion

        #region AllSure 发送手机短信验证码OK===========================
        private void user_verify_smscode(HttpContext context)
        {
            string code = DTRequest.GetFormString("code");
            string mobile = DTRequest.GetFormString("mobile");

            //校检验证码
            string result1 = verify_code(context, code);
            if (result1 != "success")
            {
                context.Response.Write(result1);
                return;
            }

            //检查手机
            if (string.IsNullOrEmpty(mobile))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"发送失败，请填写手机号码！\"}");
            }
            string result = send_verify_sms_code(context, mobile);
            if (result != "success")
            {
                context.Response.Write(result);
                return;
            }
            context.Response.Write("{\"status\":1, \"time\":\"" + userConfig.regsmsexpired + "\", \"msg\":\"手机验证码发送成功！\"}");
            return;
        }
        #endregion

        #endregion

        #region 获取视频上传地址和凭证=================================
        private void CreateUploadVideoResponse(HttpContext context)
        {
            string fileName = DTRequest.GetFormString("fileName");
            string fileTitle = DTRequest.GetFormString("fileTitle");
            string AccessKeyId = DESEncrypt.Decrypt(sysConfig.AccessKeyId, sysConfig.sysencryptstring);
            string AccessKeySecret = DESEncrypt.Decrypt(sysConfig.AccessKeySecret, sysConfig.sysencryptstring);

            if (string.IsNullOrEmpty(fileTitle) || string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(AccessKeyId) || string.IsNullOrEmpty(AccessKeySecret))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"参数错误！\"}");
                return;
            }

            try
            {
                AlibabaCloud.SDK.Vod20170321.Models.CreateUploadVideoResponse CreateUploadVideoResponse = API.Cloud.AliyunVideoHelper.CreateUploadVideoResponse(AccessKeyId, AccessKeySecret, fileName, fileTitle);

                if (CreateUploadVideoResponse == null)
                {
                    context.Response.Write("{\"status\":0, \"msg\":\"参数错误！\"}");
                    return;
                }
                else
                {
                    context.Response.Write("{\"status\":1, \"VideoId\":\"" + CreateUploadVideoResponse.Body.VideoId + "\", \"UploadAuth\":\"" + CreateUploadVideoResponse.Body.UploadAuth + "\", \"UploadAddress\":\"" + CreateUploadVideoResponse.Body.UploadAddress + "\"}");
                    return;
                }
            }
            catch (Exception e)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"消息：" + e.Message + "！\"}");
                return;
            }

        }
        #endregion

        #region 获取视频=================================
        private void getvideo(HttpContext context)
        {
            string vid = DTRequest.GetFormString("vid");
            string osssecretid = DESEncrypt.Decrypt(sysConfig.AccessKeyId, sysConfig.sysencryptstring);
            string osssecretkey = DESEncrypt.Decrypt(sysConfig.AccessKeySecret, sysConfig.sysencryptstring);

            if (string.IsNullOrEmpty(vid) || string.IsNullOrEmpty(osssecretid) || string.IsNullOrEmpty(osssecretkey))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"参数错误！\"}");
                return;
            }

            Model.aliyun_video aliyun_Video = API.Cloud.AliyunVideoHelper.GetVideoInfoRequest(vid, osssecretid, osssecretkey);

            if (aliyun_Video == null)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"参数错误！\"}");
                return;
            }
            else
            {
                string playauth = API.Cloud.AliyunVideoHelper.GetVideoPlayAuth(vid, osssecretid, osssecretkey);

                if (playauth == "")
                {
                    context.Response.Write("{\"status\":0, \"msg\":\"参数错误！\"}");
                    return;
                }

                context.Response.Write("{\"status\":1, \"vid\":\"" + vid + "\", \"playauth\":\"" + playauth + "\", \"cover\":\"" + aliyun_Video.CoverURL + "\"}");
                return;

            }
        }
        #endregion

        #region 清空微信配置信息=================================
        private void wxConfigClear(HttpContext context)
        {
            string RawUrl = DTRequest.GetFormString("url");

            CacheHelper.Insert("appId" + RawUrl, "");
            CacheHelper.Insert("nonceStr" + RawUrl, "");
            CacheHelper.Insert("timestamp" + RawUrl, "");
            CacheHelper.Insert("signature" + RawUrl, "");

            context.Response.Write("{\"status\":1, \"msg\":\"OK\"}");
            return;
        }
        #endregion

        #region 获取微信配置信息=================================
        private void wxConfig(HttpContext context)
        {
            string RawUrl = DTRequest.GetFormString("url");
            string appId = CacheHelper.Get<string>("appId" + RawUrl);
            string nonceStr = CacheHelper.Get<string>("nonceStr" + RawUrl);
            string timestamp = CacheHelper.Get<string>("timestamp" + RawUrl);
            string signature = CacheHelper.Get<string>("signature" + RawUrl);

            try
            {
                if ((string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(nonceStr)) || string.IsNullOrEmpty(signature))
                {
                    Model.weixin_account model = new BLL.weixin_account().GetModel(1); //获取公众账户信息

                    appId = model.appid;

                    string jmdata = "jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}";

                    TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);

                    timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();
                    nonceStr = Utils.GetRamStr(15);

                    Senparc.Weixin.MP.CommonAPIs.JsApiTicketContainer.Register(model.appid, model.appsecret);
                    string ticket = Senparc.Weixin.MP.CommonAPIs.JsApiTicketContainer.GetTicket(model.appid);

                    jmdata = string.Format(jmdata, ticket, nonceStr, timestamp, RawUrl);

                    signature = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(jmdata, "SHA1");

                    CacheHelper.Insert("appId" + RawUrl, appId, 120);
                    CacheHelper.Insert("nonceStr" + RawUrl, nonceStr, 120);
                    CacheHelper.Insert("timestamp" + RawUrl, timestamp, 120);
                    CacheHelper.Insert("signature" + RawUrl, signature, 120);

                    context.Response.Write("{\"status\":1, \"appId\":\"" + appId + "\", \"nonceStr\":\"" + nonceStr + "\", \"timestamp\":\"" + timestamp + "\", \"signature\":\"" + signature + "\"}");
                    return;
                }
                else
                {
                    context.Response.Write("{\"status\":1, \"appId\":\"" + appId + "\", \"nonceStr\":\"" + nonceStr + "\", \"timestamp\":\"" + timestamp + "\", \"signature\":\"" + signature + "\"}");
                    return;
                }
            }
            catch (Exception e)
            {
                CacheHelper.Insert("appId" + RawUrl, "");
                CacheHelper.Insert("nonceStr" + RawUrl, "");
                CacheHelper.Insert("timestamp" + RawUrl, "");
                CacheHelper.Insert("signature" + RawUrl, "");

                context.Response.Write("{\"status\":0, \"msg\":\"获取微信配置异常：" + e.Message + "\"}");
                return;
            }


        }
        #endregion               

        #region 用户退出
        private void user_logout(HttpContext context)
        {
            //清险Session
            HttpContext.Current.Session[DTKeys.SESSION_USER_INFO] = null;
            //清除Cookies
            Utils.WriteCookie(DTKeys.COOKIE_USER_NAME_REMEMBER, "Donal.Xms.UserName", DESEncrypt.Encrypt(DateTime.Now.ToString()), -1);
            Utils.WriteCookie(DTKeys.COOKIE_USER_PWD_REMEMBER, "Donal.Xms.PassWord", DESEncrypt.Encrypt(DateTime.Now.ToString()), -1);

            context.Response.Write("{\"status\": 1, \"msg\": \"操作成功！\"}");
            return;

        }
        #endregion

        #region 查询手机号是否唯一
        private void isExistMobile(HttpContext context)
        {
            string queryString = DTRequest.GetFormString("mobile");
            if (Regexlib.IsValidMobile(queryString))
            {
                if (new Donal.Xms.BLL.users().Exists(queryString))
                {
                    context.Response.Write("{\"status\":0, \"msg\":\"对不起，这个手机已被使用！\"}");
                }
                else
                {
                    context.Response.Write("{\"status\":1, \"msg\":\"可以使用！\"}");
                }
            }
            else
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，手机号码有误！\"}");
            }
        }
        #endregion

        #region 获取QRcode===========================
        private void get_QRcode(HttpContext context)
        {
            string data = DTRequest.GetQueryString("data");

            if (data == "")
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"对不起，参数传输有误！\"}");
                return;
            }

            data = DESEncrypt.Decrypt(data);

            if (data == "")
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"对不起，参数传输有误！\"}");
                return;
            }

            QRCodeEncoder encoder = new QRCodeEncoder
            {
                QRCodeVersion = 0
            };
            MemoryStream stream = new MemoryStream();
            encoder.Encode(data, Encoding.UTF8).Save(stream, ImageFormat.Gif);
            context.Response.ClearContent();
            context.Response.ContentType = "image/Gif";
            context.Response.BinaryWrite(stream.ToArray());
            context.Response.End();
        }
        #endregion

        #region 提交喜欢操作的处理方法===========================
        private void submit_like(HttpContext context)
        {
            StringBuilder strTxt = new StringBuilder();
            BLL.article_like bll = new BLL.article_like();
            Model.article_like model = new Model.article_like();

            int article_id = DTRequest.GetQueryInt("article_id");
            int channel_id = DTRequest.GetQueryInt("channel_id");

            if (article_id == 0)
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"对不起，参数传输有误！\"}");
                return;
            }

            //检查该文章是否存在
            Model.article artModel = new BLL.article().GetModel(channel_id, article_id);
            if (artModel == null)
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"对不起，主题不存在或已删除！\"}");
                return;
            }

            model.Ip = DTRequest.GetIP();
            model.UserAgent = DTRequest.GetUserAgent();
            model.Article_id = article_id;

            if (!bll.Exists(0, "article_id=" + article_id + " and ip='" + model.Ip + "' and userAgent = '" + model.UserAgent + "' "))
            {
                if (bll.Add(model) > 0)
                {
                    context.Response.Write("{\"status\": 1, \"msg\": \"恭喜您，提交成功,感谢您的支持！\"}");
                    return;
                }
            }
            else
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"您已经操作过了！\"}");
                return;
            }

            context.Response.Write("{\"status\": 0, \"msg\": \"对不起，保存过程中发生错误！\"}");
            return;
        }
        #endregion

        #region 提交评论的处理方法===========================
        private void comment_add(HttpContext context)
        {
            StringBuilder strTxt = new StringBuilder();
            BLL.article_comment bll = new BLL.article_comment();
            Model.article_comment model = new Model.article_comment();

            string code = DTRequest.GetFormString("txtCode");
            int channel_id = DTRequest.GetQueryInt("channel_id");
            int article_id = DTRequest.GetQueryInt("article_id");
            string _content = DTRequest.GetFormString("txtContent");
            //校检验证码
            string result = verify_code(context, code);
            if (result != "success")
            {
                context.Response.Write(result);
                return;
            }
            if (channel_id == 0)
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"对不起，频道参数传输有误！\"}");
                return;
            }
            if (article_id == 0)
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"对不起，信息参数传输有误！\"}");
                return;
            }
            if (string.IsNullOrEmpty(_content))
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"对不起，请输入评论的内容！\"}");
                return;
            }
            //检查该文章是否存在
            Model.article artModel = new BLL.article().GetModel(channel_id, article_id);
            if (artModel == null)
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"对不起，主题不存在或已删除！\"}");
                return;
            }
            //检查用户是否登录
            int user_id = 0;
            string user_name = "匿名用户";
            Model.users userModel = new Model.users();
            if (userModel != null)
            {
                user_id = userModel.id;
                user_name = userModel.user_name;
            }
            model.site_id = artModel.site_id;
            model.channel_id = artModel.channel_id;
            model.article_id = artModel.id;
            model.content = Utils.ToHtml(_content);
            model.user_id = user_id;
            model.user_name = user_name;
            model.user_ip = DTRequest.GetIP();
            model.is_lock = sysConfig.commentstatus; //审核开关
            model.add_time = DateTime.Now;
            model.is_reply = 0;
            if (bll.Add(model) > 0)
            {
                context.Response.Write("{\"status\": 1, \"msg\": \"恭喜您，评论提交成功！\"}");
                return;
            }
            context.Response.Write("{\"status\": 0, \"msg\": \"对不起，保存过程中发生错误！\"}");
            return;
        }
        #endregion

        #region 取得评论列表方法OK=============================
        private void comment_list(HttpContext context)
        {
            int channel_id = DTRequest.GetQueryInt("channel_id");
            int article_id = DTRequest.GetQueryInt("article_id");
            int page_index = DTRequest.GetQueryInt("page_index");
            int page_size = DTRequest.GetQueryInt("page_size");
            int totalcount;
            StringBuilder strTxt = new StringBuilder();

            if (channel_id == 0 || article_id == 0 || page_size == 0)
            {
                context.Response.Write("获取失败，传输参数有误！");
                return;
            }

            BLL.article_comment bll = new BLL.article_comment();
            DataSet ds = bll.GetList(page_size, page_index, string.Format("is_lock=0 and channel_id={0} and article_id={1}",
                channel_id.ToString(), article_id.ToString()), "add_time asc", out totalcount);
            //如果记录存在
            if (ds.Tables[0].Rows.Count > 0)
            {
                strTxt.Append("[");
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow dr = ds.Tables[0].Rows[i];
                    strTxt.Append("{");
                    strTxt.Append("\"user_id\":" + dr["user_id"]);
                    strTxt.Append(",\"user_name\":\"" + dr["user_name"] + "\"");
                    if (Convert.ToInt32(dr["user_id"]) > 0)
                    {
                        Model.users userModel = new BLL.users().GetModel(Convert.ToInt32(dr["user_id"]));
                        if (userModel != null)
                        {
                            strTxt.Append(",\"avatar\":\"" + userModel.avatar + "\"");
                        }
                    }
                    strTxt.Append("");
                    strTxt.Append(",\"content\":\"" + Microsoft.JScript.GlobalObject.escape(dr["content"]) + "\"");
                    strTxt.Append(",\"add_time\":\"" + dr["add_time"] + "\"");
                    strTxt.Append(",\"is_reply\":" + dr["is_reply"]);
                    if (Convert.ToInt32(dr["is_reply"]) == 1)
                    {
                        strTxt.Append(",\"reply_content\":\"" + Microsoft.JScript.GlobalObject.escape(dr["reply_content"]) + "\"");
                        strTxt.Append(",\"reply_time\":\"" + dr["reply_time"] + "\"");
                    }
                    strTxt.Append("}");
                    //是否加逗号
                    if (i < ds.Tables[0].Rows.Count - 1)
                    {
                        strTxt.Append(",");
                    }

                }
                strTxt.Append("]");
            }
            context.Response.Write(strTxt.ToString());
        }
        #endregion

        #region 验证用户名是否可用OK===========================
        private void validate_username(HttpContext context)
        {
            string username = DTRequest.GetString("param");
            //如果为Null，退出
            if (string.IsNullOrEmpty(username))
            {
                context.Response.Write("{ \"info\":\"用户名不可为空\", \"status\":\"n\" }");
                return;
            }
            //过滤注册用户名字符
            string[] strArray = userConfig.regkeywords.Split(',');
            foreach (string s in strArray)
            {
                if (s.ToLower() == username.ToLower())
                {
                    context.Response.Write("{ \"info\":\"该用户名不可用\", \"status\":\"n\" }");
                    return;
                }
            }
            BLL.users bll = new BLL.users();
            //查询数据库
            if (!bll.Exists(username.Trim()))
            {
                context.Response.Write("{ \"info\":\"该用户名可用\", \"status\":\"y\" }");
                return;
            }
            context.Response.Write("{ \"info\":\"该用户名已被注册\", \"status\":\"n\" }");
            return;
        }
        #endregion

        #region 检查用户是否登录OK=============================
        private void user_check_login(HttpContext context)
        {
            //检查用户是否登录
            Model.users model = new Model.users();
            if (model == null)
            {
                context.Response.Write("{\"status\":0, \"username\":\"匿名用户\"}");
                return;
            }
            context.Response.Write("{\"status\":1, \"username\":\"" + model.user_name + "\"}");
        }
        #endregion        

        #region 发送注册验证邮件OK=============================
        private void user_verify_email(HttpContext context)
        {
            int site_id = DTRequest.GetQueryInt("site_id"); //当前站点ID
            string sitepath = new BLL.sites().GetBuildPath(site_id); //当前站点目录
            string username = Utils.ToHtml(DTRequest.GetFormString("username"));

            if (site_id == 0 || string.IsNullOrEmpty(sitepath))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"站点传输参数有误！\"}");
                return;
            }
            if (string.IsNullOrEmpty(username))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"请检查用户名是否正确！\"}");
                return;
            }
            //检查邮件是否过快
            string cookie = Utils.GetCookie(DTKeys.COOKIE_USER_EMAIL);
            if (cookie == username)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"邮件发送间隔为二十分钟，请稍候再提交吧！\"}");
                return;
            }
            Model.users model = new BLL.users().GetModel(username);
            if (model == null)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"该用户不存在或已删除！\"}");
                return;
            }
            if (model.status != 1)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"该用户不需要邮箱验证！\"}");
                return;
            }
            string result = send_verify_email(sitepath, model);
            if (result != "success")
            {
                context.Response.Write(result);
                return;
            }
            context.Response.Write("{\"status\":1, \"msg\":\"邮件已发送，请进入邮箱查看！\"}");
            Utils.WriteCookie(DTKeys.COOKIE_USER_EMAIL, username, 20); //20分钟内无重复发送
            return;
        }
        #endregion

        #region 修改用户信息OK=================================
        private void user_info_edit(HttpContext context)
        {
            //检查用户是否登录
            Model.users model = new Model.users();
            if (model == null)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，用户尚未登录或已超时！\"}");
                return;
            }
            string nick_name = Utils.ToHtml(DTRequest.GetFormString("txtNickName"));
            string sex = DTRequest.GetFormString("rblSex");
            string birthday = DTRequest.GetFormString("txtBirthday");
            string email = Utils.ToHtml(DTRequest.GetFormString("txtEmail"));
            string mobile = Utils.ToHtml(DTRequest.GetFormString("txtMobile"));
            string telphone = Utils.ToHtml(DTRequest.GetFormString("txtTelphone"));
            string qq = Utils.ToHtml(DTRequest.GetFormString("txtQQ"));
            string msn = Utils.ToHtml(DTRequest.GetFormString("txtMsn"));
            string province = Utils.ToHtml(DTRequest.GetFormString("txtProvince"));
            string city = Utils.ToHtml(DTRequest.GetFormString("txtCity"));
            string area = Utils.ToHtml(DTRequest.GetFormString("txtArea"));
            string address = Utils.ToHtml(context.Request.Form["txtAddress"]);
            //检查昵称
            if (string.IsNullOrEmpty(nick_name))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，请输入您的姓名昵称！\"}");
                return;
            }
            //检查省市区
            if (string.IsNullOrEmpty(province) || string.IsNullOrEmpty(city) || string.IsNullOrEmpty(area))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，请选择您所在的省市区！\"}");
                return;
            }
            BLL.users bll = new BLL.users();
            //检查手机，如开启手机注册或使用手机登录需要检查
            if (userConfig.regstatus == 2 || userConfig.mobilelogin == 1)
            {
                if (string.IsNullOrEmpty(mobile))
                {
                    context.Response.Write("{\"status\":0, \"msg\":\"对不起，请输入您的手机号码！\"}");
                    return;
                }
                if (model.mobile != mobile && bll.ExistsMobile(mobile))
                {
                    context.Response.Write("{\"status\":0, \"msg\":\"对不起，该手机号码已被使用！\"}");
                    return;
                }
            }
            //检查邮箱，如开启邮箱注册或使用邮箱登录需要检查
            if (userConfig.regstatus == 3 || userConfig.emaillogin == 1)
            {
                if (string.IsNullOrEmpty(email))
                {
                    context.Response.Write("{\"status\":0, \"msg\":\"对不起，请输入您的电子邮箱！\"}");
                    return;
                }
                if (model.email != email && bll.ExistsEmail(email))
                {
                    context.Response.Write("{\"status\":0, \"msg\":\"对不起，该电子邮箱已被使用！\"}");
                    return;
                }
            }

            //开始写入数据库
            model.nick_name = nick_name;
            model.sex = sex;
            DateTime _birthday;
            if (DateTime.TryParse(birthday, out _birthday))
            {
                model.birthday = _birthday;
            }
            model.email = email;
            model.mobile = mobile;
            model.telphone = telphone;
            model.qq = qq;

            model.area = province + "," + city + "," + area;
            model.address = address;

            bll.Update(model);
            context.Response.Write("{\"status\":1, \"msg\":\"账户资料已修改成功！\"}");
            return;
        }
        #endregion

        #region 确认裁剪用户头像OK=============================
        private void user_avatar_crop(HttpContext context)
        {
            //检查用户是否登录
            Model.users model = new Model.users();
            if (model == null)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，用户尚未登录或已超时！\"}");
                return;
            }
            string fileName = DTRequest.GetFormString("hideFileName");
            int x1 = DTRequest.GetFormInt("hideX1");
            int y1 = DTRequest.GetFormInt("hideY1");
            int w = DTRequest.GetFormInt("hideWidth");
            int h = DTRequest.GetFormInt("hideHeight");
            //检查是否图片

            //检查参数
            if (string.IsNullOrEmpty(fileName) || w == 0 || h == 0)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，请先上传一张图片！\"}");
                return;
            }
            //取得保存的新文件名
            UpLoad upFiles = new UpLoad();
            string result = upFiles.CropSaveAs(fileName, 180, 180, w, h, x1, y1);
            Dictionary<string, object> dic = JsonHelper.DataRowFromJSON(result);
            if (dic["status"].ToString() == "0")
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"图片裁剪过程中发生意外错误！\"}");
                return;
            }
            //删除原用户头像
            upFiles.DeleteFile(model.avatar);
            model.avatar = dic["path"].ToString();
            //修改用户头像
            new BLL.users().UpdateField(model.id, "avatar='" + model.avatar + "'");
            context.Response.Write("{\"status\": 1, \"msg\": \"头像上传成功！\", \"avatar\": \"" + model.avatar + "\"}");
            return;
        }
        #endregion

        #region 修改登录密码OK=================================
        private void user_password_edit(HttpContext context)
        {
            //检查用户是否登录
            Model.users model = new Model.users();
            if (model == null)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，用户尚未登录或已超时！\"}");
                return;
            }
            int user_id = model.id;
            string oldpassword = DTRequest.GetFormString("txtOldPassword");
            string password = DTRequest.GetFormString("txtPassword");
            //检查输入的旧密码
            if (string.IsNullOrEmpty(oldpassword))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"请输入您的旧登录密码！\"}");
                return;
            }
            //检查输入的新密码
            if (string.IsNullOrEmpty(password))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"请输入您的新登录密码！\"}");
                return;
            }
            //旧密码是否正确
            if (model.password != DESEncrypt.Encrypt(oldpassword, model.salt))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，您输入的旧密码不正确！\"}");
                return;
            }
            //执行修改操作
            model.password = DESEncrypt.Encrypt(password, model.salt);
            new BLL.users().Update(model);
            context.Response.Write("{\"status\":1, \"msg\":\"您的密码已修改成功，请记住新密码！\"}");
            return;
        }
        #endregion

        #region 用户取回密码OK=================================
        private void user_getpassword(HttpContext context)
        {
            int site_id = DTRequest.GetQueryInt("site_id");//当前站点ID
            string sitepath = new BLL.sites().GetBuildPath(site_id);//站点目录
            string code = DTRequest.GetFormString("txtCode");
            string type = DTRequest.GetFormString("txtType");
            string username = DTRequest.GetFormString("txtUserName").Trim();
            //检查站点目录
            if (site_id == 0 || string.IsNullOrEmpty(sitepath))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，站点传输参数有误！\"}");
                return;
            }
            //检查用户名
            if (string.IsNullOrEmpty(username))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，用户名不可为空！\"}");
                return;
            }
            //检查取回密码类型
            if (string.IsNullOrEmpty(type))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，请选择取回密码类型！\"}");
                return;
            }
            //校检验证码
            string result = verify_code(context, code);
            if (result != "success")
            {
                context.Response.Write(result);
                return;
            }
            //检查用户信息
            BLL.users bll = new BLL.users();
            Model.users model = bll.GetModel(username);
            if (model == null)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，您输入的用户名不存在！\"}");
                return;
            }
            //发送取回密码的短信或邮件
            if (type.ToLower() == "mobile") //使用手机取回密码
            {
                #region 发送短信==================
                if (string.IsNullOrEmpty(model.mobile))
                {
                    context.Response.Write("{\"status\":0, \"msg\":\"您尚未绑定手机号码，无法取回密码！\"}");
                    return;
                }
                Model.sms_template smsModel = new BLL.sms_template().GetModel("usercode"); //取得短信内容
                if (smsModel == null)
                {
                    context.Response.Write("{\"status\":0, \"msg\":\"发送失败，短信模板不存在，请联系管理员！\"}");
                }
                string strcode = Utils.Number(4); //随机验证码
                //检查是否重复提交
                BLL.user_code codeBll = new BLL.user_code();
                Model.user_code codeModel;
                codeModel = codeBll.GetModel(username, DTEnums.CodeEnum.RegVerify.ToString(), "d");
                if (codeModel == null)
                {
                    codeModel = new Model.user_code();
                    //写入数据库
                    codeModel.user_id = model.id;
                    codeModel.user_name = model.user_name;
                    codeModel.type = DTEnums.CodeEnum.Password.ToString();
                    codeModel.str_code = strcode;
                    codeModel.eff_time = DateTime.Now.AddMinutes(userConfig.regsmsexpired);
                    codeModel.add_time = DateTime.Now;
                    codeBll.Add(codeModel);
                }
                //替换标签
                string msgContent = smsModel.content;
                msgContent = msgContent.Replace("{webname}", sysConfig.webname);
                msgContent = msgContent.Replace("{weburl}", sysConfig.weburl);
                msgContent = msgContent.Replace("{webtel}", sysConfig.webtel);
                msgContent = msgContent.Replace("{code}", codeModel.str_code);
                msgContent = msgContent.Replace("{valid}", userConfig.regsmsexpired.ToString());
                //发送短信
                string tipMsg = string.Empty;
                bool result1 = new BLL.sms_message().Send(model.mobile, msgContent, "", out tipMsg);
                if (!result1)
                {
                    context.Response.Write("{\"status\":0, \"msg\":\"发送失败，" + tipMsg + "\"}");
                    return;
                }
                context.Response.Write("{\"status\":1, \"msg\":\"手机验证码发送成功！\", \"url\":\""
                    + new BasePage().getlink(sitepath, new BasePage().linkurl(0, "repassword", "?action=mobile&username=" + Utils.UrlEncode(model.user_name))) + "\"}");
                return;
                #endregion
            }
            else if (type.ToLower() == "email") //使用邮箱取回密码
            {
                #region 发送邮件==================
                if (string.IsNullOrEmpty(model.email))
                {
                    context.Response.Write("{\"status\":0, \"msg\":\"您尚未绑定邮箱，无法取回密码！\"}");
                    return;
                }
                //生成随机码
                string strcode = Utils.GetCheckCode(20);
                //获得邮件内容
                Model.mail_template mailModel = new BLL.mail_template().GetModel("getpassword");
                if (mailModel == null)
                {
                    context.Response.Write("{\"status\":0, \"msg\":\"邮件发送失败，邮件模板内容不存在！\"}");
                    return;
                }
                //检查是否重复提交
                BLL.user_code codeBll = new BLL.user_code();
                Model.user_code codeModel;
                codeModel = codeBll.GetModel(username, DTEnums.CodeEnum.RegVerify.ToString(), "d");
                if (codeModel == null)
                {
                    codeModel = new Model.user_code();
                    //写入数据库
                    codeModel.user_id = model.id;
                    codeModel.user_name = model.user_name;
                    codeModel.type = DTEnums.CodeEnum.Password.ToString();
                    codeModel.str_code = strcode;
                    codeModel.eff_time = DateTime.Now.AddDays(userConfig.regemailexpired);
                    codeModel.add_time = DateTime.Now;
                    codeBll.Add(codeModel);
                }
                //替换模板内容
                string titletxt = mailModel.maill_title;
                string bodytxt = mailModel.content;
                titletxt = titletxt.Replace("{webname}", sysConfig.webname);
                titletxt = titletxt.Replace("{username}", model.user_name);
                bodytxt = bodytxt.Replace("{webname}", sysConfig.webname);
                bodytxt = bodytxt.Replace("{weburl}", sysConfig.weburl);
                bodytxt = bodytxt.Replace("{webtel}", sysConfig.webtel);
                bodytxt = bodytxt.Replace("{valid}", userConfig.regemailexpired.ToString());
                bodytxt = bodytxt.Replace("{username}", model.user_name);
                bodytxt = bodytxt.Replace("{linkurl}", "http://" + HttpContext.Current.Request.Url.Authority.ToLower()
                    + new BasePage().getlink(sitepath, new BasePage().linkurl(0, "repassword", "?action=email&code=" + codeModel.str_code)));
                //发送邮件
                try
                {
                    DTMail.sendMail(sysConfig.emailsmtp,
                        sysConfig.emailssl,
                        sysConfig.emailusername,
                        DESEncrypt.Decrypt(sysConfig.emailpassword, sysConfig.sysencryptstring),
                        sysConfig.emailnickname,
                        sysConfig.emailfrom,
                        model.email,
                        titletxt, bodytxt);
                }
                catch
                {
                    context.Response.Write("{\"status\":0, \"msg\":\"邮件发送失败，请联系本站管理员！\"}");
                    return;
                }
                context.Response.Write("{\"status\":1, \"msg\":\"邮件发送成功，请登录邮箱查看邮件！\"}");
                return;
                #endregion
            }
            context.Response.Write("{\"status\":0, \"msg\":\"发生未知错误，请检查参数是否正确！\"}");
            return;
        }
        #endregion

        #region 用户重设密码OK=================================
        private void user_repassword(HttpContext context)
        {
            string strcode = DTRequest.GetFormString("hideCode"); //取回密码字符串
            string password = DTRequest.GetFormString("txtPassword"); //重设后的密码

            //检查验证字符串
            if (string.IsNullOrEmpty(strcode))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，校检码字符串不能为空！\"}");
                return;
            }
            //检查输入的新密码
            if (string.IsNullOrEmpty(password))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，请输入您的新密码！\"}");
                return;
            }

            BLL.user_code codeBll = new BLL.user_code();
            Model.user_code codeModel = codeBll.GetModel(strcode);
            if (codeModel == null)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，校检码不存在或已过期！\"}");
                return;
            }
            //验证用户是否存在
            BLL.users userBll = new BLL.users();
            if (!userBll.Exists(codeModel.user_id))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，该用户不存在或已被删除！\"}");
                return;
            }
            Model.users userModel = userBll.GetModel(codeModel.user_id);
            //执行修改操作
            userModel.password = DESEncrypt.Encrypt(password, userModel.salt);
            userBll.Update(userModel);
            //更改验证字符串状态
            codeModel.count = 1;
            codeModel.status = 1;
            codeBll.Update(codeModel);
            context.Response.Write("{\"status\":1, \"msg\":\"修改密码成功，请记住新密码！\"}");
            return;
        }
        #endregion

        #region 申请邀请码OK===================================
        private void user_invite_code(HttpContext context)
        {
            //检查用户是否登录
            Model.users model = new Model.users();
            if (model == null)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，用户尚未登录或已超时！\"}");
                return;
            }
            //检查是否开启邀请注册
            if (userConfig.regstatus != 4)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，系统不允许通过邀请注册！\"}");
                return;
            }
            BLL.user_code codeBll = new BLL.user_code();
            //检查申请是否超过限制
            if (userConfig.invitecodenum > 0)
            {
                int result = codeBll.GetCount("user_name='" + model.user_name + "' and type='" + DTEnums.CodeEnum.Register.ToString() + "' and datediff(d,add_time,getdate())=0");
                if (result >= userConfig.invitecodenum)
                {
                    context.Response.Write("{\"status\":0, \"msg\":\"对不起，您申请邀请码的数量已超过每天限制！\"}");
                    return;
                }
            }
            //删除过期的邀请码
            codeBll.Delete("type='" + DTEnums.CodeEnum.Register.ToString() + "' and status=1 or datediff(d,eff_time,getdate())>0");
            //随机取得邀请码
            string str_code = Utils.GetCheckCode(8);
            Model.user_code codeModel = new Model.user_code();
            codeModel.user_id = model.id;
            codeModel.user_name = model.user_name;
            codeModel.type = DTEnums.CodeEnum.Register.ToString();
            codeModel.str_code = str_code;
            codeModel.user_ip = DTRequest.GetIP();
            if (userConfig.invitecodeexpired > 0)
            {
                codeModel.eff_time = DateTime.Now.AddDays(userConfig.invitecodeexpired);
            }
            else
            {
                codeModel.eff_time = DateTime.Now.AddDays(1);
            }
            codeBll.Add(codeModel);
            context.Response.Write("{\"status\":1, \"msg\":\"恭喜您，申请邀请码已成功！\"}");
            return;
        }
        #endregion

        #region 用户在线充值OK=================================
        private void user_amount_recharge(HttpContext context)
        {
            //检查用户是否登录
            Model.users model = new Model.users();
            if (model == null)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，用户尚未登录或已超时！\"}");
                return;
            }
            int site_id = DTRequest.GetQueryInt("site_id"); //当前站点ID
            string sitepath = new BLL.sites().GetBuildPath(site_id); //站点目录
            decimal amount = DTRequest.GetFormDecimal("order_amount", 0);
            int payment_id = DTRequest.GetFormInt("payment_id");
            //检查站点目录
            if (string.IsNullOrEmpty(sitepath))
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"错误提示：站点传输参数不正确！\"}");
                return;
            }
            if (amount == 0)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，请输入正确的充值金额！\"}");
                return;
            }
            if (payment_id == 0)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，请选择正确的支付方式！\"}");
                return;
            }
            if (!new BLL.payment().Exists(payment_id))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，支付方式不存在或已删除！\"}");
                return;
            }
            //生成订单号
            string order_no = "R" + Utils.GetOrderNumber(); //订单号R开头为充值订单

            //保存成功后返回订单号
            context.Response.Write("{\"status\":1, \"msg\":\"订单保存成功！\", \"url\":\""
                + new Web.UI.BasePage().getlink(sitepath, new Web.UI.BasePage().linkurl(0, "payment", "?action=confirm&order_no=" + order_no)) + "\"}");
            return;

        }
        #endregion

        #region 发布站内短消息OK===============================
        private void user_message_add(HttpContext context)
        {
            //检查用户是否登录
            Model.users model = new Model.users();
            if (model == null)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，用户尚未登录或已超时！\"}");
                return;
            }
            string code = context.Request.Form["txtCode"];
            string send_save = DTRequest.GetFormString("sendSave");
            string user_name = Utils.ToHtml(DTRequest.GetFormString("txtUserName"));
            string title = Utils.ToHtml(DTRequest.GetFormString("txtTitle"));
            string content = Utils.ToHtml(DTRequest.GetFormString("txtContent"));
            //校检验证码
            string result = verify_code(context, code);
            if (result != "success")
            {
                context.Response.Write(result);
                return;
            }
            //检查用户名
            if (string.IsNullOrEmpty(user_name) || !new BLL.users().Exists(user_name))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，该用户不存在或已删除！\"}");
                return;
            }
            //检查标题
            if (string.IsNullOrEmpty(title))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，请输入短消息标题！\"}");
                return;
            }
            //检查内容
            if (string.IsNullOrEmpty(content))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，请输入短消息内容！\"}");
                return;
            }
            //保存数据
            Model.user_message modelMessage = new Model.user_message();
            modelMessage.type = 2;
            modelMessage.post_user_name = model.user_name;
            modelMessage.accept_user_name = user_name;
            modelMessage.title = title;
            modelMessage.content = Utils.ToHtml(content);
            new BLL.user_message().Add(modelMessage);
            if (send_save == "true") //保存到收件箱
            {
                modelMessage.type = 3;
                new BLL.user_message().Add(modelMessage);
            }
            context.Response.Write("{\"status\":1, \"msg\":\"发布短信息成功！\"}");
            return;
        }
        #endregion

        #region 编辑用户收货地址OK=============================
        private void user_address_edit(HttpContext context)
        {
            //检查用户是否登录
            Model.users userModel = new Model.users();
            Model.user_addr_book model = new Model.user_addr_book();
            BLL.user_addr_book bll = new BLL.user_addr_book();
            if (userModel == null)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，用户尚未登录或已超时！\"}");
                return;
            }
            int id = DTRequest.GetQueryInt("id", 0);
            if (id > 0)
            {
                if (!bll.Exists(id, userModel.user_name))
                {
                    context.Response.Write("{\"status\":0, \"msg\":\"对不起，收货地址不存在或已删除！\"}");
                    return;
                }
                model = bll.GetModel(id);
            }
            string code = DTRequest.GetFormString("txtCode");
            string accept_name = DTRequest.GetFormString("txtAcceptName");
            string province = Utils.ToHtml(DTRequest.GetFormString("txtProvince"));
            string city = Utils.ToHtml(DTRequest.GetFormString("txtCity"));
            string area = Utils.ToHtml(DTRequest.GetFormString("txtArea"));
            string address = Utils.ToHtml(context.Request.Form["txtAddress"]);
            string mobile = Utils.ToHtml(DTRequest.GetFormString("txtMobile"));
            string telphone = Utils.ToHtml(DTRequest.GetFormString("txtTelphone"));
            string email = Utils.ToHtml(DTRequest.GetFormString("txtEmail"));
            string post_code = Utils.ToHtml(DTRequest.GetFormString("txtPostCode"));

            //校检验证码
            string result = verify_code(context, code);
            if (result != "success")
            {
                context.Response.Write(result);
                return;
            }
            //检查收件人
            if (string.IsNullOrEmpty(accept_name))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，请输入收件人姓名！\"}");
                return;
            }
            //检查省市区
            if (string.IsNullOrEmpty(province) || string.IsNullOrEmpty(city) || string.IsNullOrEmpty(area))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，请选择您所在的省市区！\"}");
                return;
            }
            //检查手机
            if (string.IsNullOrEmpty(mobile))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，请输入收件人的手机！\"}");
                return;
            }
            //保存数据
            model.user_id = userModel.id;
            model.user_name = userModel.user_name;
            model.accept_name = accept_name;
            model.area = province + "," + city + "," + area;
            model.address = address;
            model.mobile = mobile;
            model.telphone = telphone;
            model.email = email;
            model.post_code = post_code;
            if (id > 0)
            {
                new BLL.user_addr_book().Update(model);
                context.Response.Write("{\"status\":1, \"msg\":\"修改收货地址成功！\"}");
            }
            else
            {
                new BLL.user_addr_book().Add(model);
                context.Response.Write("{\"status\":1, \"msg\":\"新增收货地址成功！\"}");
            }
            return;
        }
        #endregion                

        #region 删除用户积分明细OK=============================
        private void user_point_delete(HttpContext context)
        {
            //检查用户是否登录
            Model.users model = new Model.users();
            if (model == null)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，用户尚未登录或已超时！\"}");
                return;
            }
            string check_id = DTRequest.GetFormString("checkId");
            if (string.IsNullOrEmpty(check_id))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"删除失败，请检查传输参数！\"}");
                return;
            }
            string[] arrId = check_id.Split(',');
            for (int i = 0; i < arrId.Length; i++)
            {
                int id = Utils.StrToInt(arrId[i], 0);
                if (id > 0)
                {
                    new BLL.user_point_log().Delete(id, model.user_name);
                }
            }
            context.Response.Write("{\"status\":1, \"msg\":\"积分明细删除成功！\"}");
            return;
        }
        #endregion

        #region 删除用户收支明细OK=============================
        private void user_amount_delete(HttpContext context)
        {
            //检查用户是否登录
            Model.users model = new Model.users();
            if (model == null)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，用户尚未登录或已超时！\"}");
                return;
            }
            string check_id = DTRequest.GetFormString("checkId");
            if (string.IsNullOrEmpty(check_id))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"删除失败，请检查传输参数！\"}");
                return;
            }
            string[] arrId = check_id.Split(',');
            for (int i = 0; i < arrId.Length; i++)
            {
                int id = Utils.StrToInt(arrId[i], 0);
                if (id > 0)
                {
                    new BLL.user_amount_log().Delete(id, model.user_name);
                }
            }
            context.Response.Write("{\"status\":1, \"msg\":\"收支明细删除成功！\"}");
            return;
        }
        #endregion

        #region 删除用户充值记录OK=============================
        private void user_recharge_delete(HttpContext context)
        {
            //检查用户是否登录
            Model.users model = new Model.users();
            if (model == null)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，用户尚未登录或已超时！\"}");
                return;
            }
            string check_id = DTRequest.GetFormString("checkId");
            if (string.IsNullOrEmpty(check_id))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"删除失败，请检查传输参数！\"}");
                return;
            }
            string[] arrId = check_id.Split(',');
            for (int i = 0; i < arrId.Length; i++)
            {
                int id = Utils.StrToInt(arrId[i], 0);
                if (id > 0)
                {
                    new BLL.user_recharge().Delete(id, model.user_name);
                }
            }
            context.Response.Write("{\"status\":1, \"msg\":\"充值记录删除成功！\"}");
            return;
        }
        #endregion

        #region 删除短消息OK===================================
        private void user_message_delete(HttpContext context)
        {
            //检查用户是否登录
            Model.users model = new Model.users();
            if (model == null)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，用户尚未登录或已超时！\"}");
                return;
            }
            string check_id = DTRequest.GetFormString("checkId");
            if (string.IsNullOrEmpty(check_id))
            {
                context.Response.Write("{\"status\":0, \"msg\":\"删除失败，请检查传输参数！\"}");
                return;
            }
            string[] arrId = check_id.Split(',');
            for (int i = 0; i < arrId.Length; i++)
            {
                int id = Utils.StrToInt(arrId[i], 0);
                if (id > 0)
                {
                    new BLL.user_message().Delete(id, model.user_name);
                }
            }
            context.Response.Write("{\"status\":1, \"msg\":\"删除短消息成功！\"}");
            return;
        }
        #endregion

        #region 获取对应的商品信息OK===========================
        private void get_article_goods_info(HttpContext context)
        {
            int channel_id = DTRequest.GetInt("channel_id", 0);
            int article_id = DTRequest.GetInt("article_id", 0);
            string spec_ids = DTRequest.GetString("ids");
            if (channel_id == 0 || article_id == 0)
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"对不起，传输参数不正确！\"}");
                return;
            }
            if (string.IsNullOrEmpty(spec_ids))
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"对不起，传输参数不正确！\"}");
                return;
            }
            //查询商品信息
            Model.article_goods goodsModel = new BLL.article_goods().GetModel(channel_id, article_id, spec_ids);
            if (goodsModel == null)
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"对不起，暂无查到商品信息！\"}");
                return;
            }
            //查询是否登录，有则查询会员价格
            Model.users userModel = new Model.users();
            if (userModel != null)
            {
                //查询会员组价格
                Model.user_group_price userPriceModel = new BLL.user_group_price().GetModel(userModel.group_id, goodsModel.id);
                if (userPriceModel != null)
                {
                    goodsModel.sell_price = userPriceModel.price;
                }
                else
                {
                    //查询会员组折扣
                    Model.user_groups groupModel = new BLL.user_groups().GetModel(userModel.group_id);
                    if (groupModel != null)
                    {
                        goodsModel.sell_price = goodsModel.sell_price * groupModel.discount / 100;
                    }
                }
            }
            //以JSON格式输出商品信息
            context.Response.Write("{\"status\": \"1\", \"id\": \"" + goodsModel.id + "\", \"article_id\": \"" + goodsModel.article_id + "\", \"goods_id\": \"" + goodsModel.id
                + "\", \"goods_no\": \"" + goodsModel.goods_no + "\", \"spec_ids\": \"" + goodsModel.spec_ids + "\", \"spec_text\": \"" + goodsModel.spec_text
                + "\", \"stock_quantity\": \"" + goodsModel.stock_quantity + "\", \"market_price\": \"" + goodsModel.market_price + "\", \"sell_price\": \"" + goodsModel.sell_price + "\"}");
        }
        #endregion



        #region 统计及输出阅读次数OK===========================
        private void view_article_click(HttpContext context)
        {
            int channel_id = DTRequest.GetInt("channel_id", 0);
            int article_id = DTRequest.GetInt("id", 0);
            int click = DTRequest.GetInt("click", 0);
            int hide = DTRequest.GetInt("hide", 0);
            int count = 0;
            if (channel_id > 0 && article_id > 0)
            {
                BLL.article bll = new BLL.article();
                count = bll.GetClick(channel_id, article_id);
                if (click > 0)
                {
                    bll.UpdateField(channel_id, article_id, "click=click+1");
                }
            }
            if (hide == 0)
            {
                context.Response.Write("document.write('" + count + "');");
            }
        }
        #endregion

        #region 输出评论总数OK=================================
        private void view_comment_count(HttpContext context)
        {
            int channel_id = DTRequest.GetInt("channel_id", 0);
            int article_id = DTRequest.GetInt("id", 0);
            int count = 0;
            if (channel_id > 0 && article_id > 0)
            {
                count = new BLL.article_comment().GetCount("is_lock=0 and channel_id=" + channel_id + " and article_id=" + article_id);
            }
            context.Response.Write("document.write('" + count + "');");
        }
        #endregion

        #region 输出附件下载总数OK=============================
        private void view_attach_count(HttpContext context)
        {
            int channel_id = DTRequest.GetInt("channel_id", 0); //频道ID
            int id = DTRequest.GetInt("id", 0); //附件ID或文章ID
            string view = DTRequest.GetString("view");
            int count = 0;
            if (id > 0)
            {
                if (view.ToLower() == "count")
                {
                    count = new BLL.article_attach().GetCountNum(channel_id, id); //频道和文章ID
                }
                else
                {
                    count = new BLL.article_attach().GetDownNum(id); //附件ID
                }
            }
            context.Response.Write("document.write('" + count + "');");
        }
        #endregion



        #region 通用外理方法=================================

        #region 校检网站验证码OK===============================
        private string verify_code(HttpContext context, string strcode)
        {
            if (string.IsNullOrEmpty(strcode))
            {
                return "{\"status\":0, \"msg\":\"对不起，请输入验证码！\"}";
            }
            if (context.Session[DTKeys.SESSION_CODE] == null)
            {
                return "{\"status\":0, \"msg\":\"对不起，验证码超时或已过期，请点击刷新！\"}";
            }
            if (strcode.ToLower() != (context.Session[DTKeys.SESSION_CODE].ToString()).ToLower())
            {
                return "{\"status\":0, \"msg\":\"您输入的验证码与系统的不一致！\"}";
            }
            context.Session[DTKeys.SESSION_CODE] = null;
            return "success";
        }
        #endregion

        #region 校检手机验证码OK===============================
        private string verify_sms_code(HttpContext context, string strcode)
        {
            if (string.IsNullOrEmpty(strcode))
            {
                return "{\"status\":0, \"msg\":\"对不起，请输入手机验证码！\"}";
            }
            if (context.Session[DTKeys.SESSION_SMS_CODE] == null)
            {
                return "{\"status\":0, \"msg\":\"对不起，手机验证码超时或已过期，请重新获取！\"}";
            }
            if (strcode.ToLower() != (context.Session[DTKeys.SESSION_SMS_CODE].ToString()).ToLower())
            {
                return "{\"status\":0, \"msg\":\"您输入的手机验证码与系统的不一致！\"}";
            }
            context.Session[DTKeys.SESSION_SMS_CODE] = null;
            return "success";
        }
        #endregion

        #region 邀请注册处理方法OK=============================
        private string verify_invite_reg(string user_name, string invite_code)
        {
            if (string.IsNullOrEmpty(invite_code))
            {
                return "{\"status\":0, \"msg\":\"邀请码不能为空！\"}";
            }
            BLL.user_code codeBll = new BLL.user_code();
            Model.user_code codeModel = codeBll.GetModel(invite_code);
            if (codeModel == null)
            {
                return "{\"status\":0, \"msg\":\"邀请码不正确或已过期！\"}";
            }
            if (userConfig.invitecodecount > 0)
            {
                if (codeModel.count >= userConfig.invitecodecount)
                {
                    codeModel.status = 1;
                    return "{\"status\":0, \"msg\":\"该邀请码已经被使用！\"}";
                }
            }

            //更改邀请码状态
            codeModel.count += 1;
            codeBll.Update(codeModel);
            return "success";
        }
        #endregion

        #region 发送手机短信验证码OK===========================
        private string send_verify_sms_code(HttpContext context, string mobile)
        {
            string strcode = string.Empty;

            //检查手机
            if (string.IsNullOrEmpty(mobile))
            {
                return "{\"status\":0, \"msg\":\"发送失败，请填写手机号码！\"}";
            }
            //检查是否过期
            string cookie = Utils.GetCookie(DTKeys.COOKIE_USER_MOBILE);
            if (cookie == mobile)
            {
                strcode = Utils.GetCookie(DTKeys.SESSION_SMS_CODE);
                context.Session[DTKeys.SESSION_SMS_CODE] = strcode;

                return "{\"status\":1, \"time\":\"" + userConfig.regsmsexpired + "\", \"msg\":\"已发送短信，" + userConfig.regsmsexpired + "分钟后再试！\"}";
            }

            strcode = Utils.Number(5); //随机验证码

            //发送短信
            string tipMsg = string.Empty;
            bool result = new BLL.sms_message().Send(mobile, "usercode", "{\"code\":\"" + strcode + "\"}", out tipMsg);
            if (!result)
            {
                return "{\"status\":0, \"msg\":\"发送失败，" + tipMsg + "\"}";
            }
            //写入SESSION，保存验证码
            context.Session[DTKeys.SESSION_SMS_CODE] = strcode;
            Utils.WriteCookie(DTKeys.COOKIE_USER_MOBILE, mobile, userConfig.regsmsexpired); //规定时间内无重复发送
            Utils.WriteCookie(DTKeys.SESSION_SMS_CODE, strcode, userConfig.regsmsexpired); //规定时间内无重复发送

            return "success";
        }
        #endregion

        #region Email验证发送邮件OK============================
        private string send_verify_email(string sitepath, Model.users userModel)
        {
            //生成随机码
            string strcode = Utils.GetCheckCode(20);
            BLL.user_code codeBll = new BLL.user_code();
            Model.user_code codeModel;
            //检查是否重复提交
            codeModel = codeBll.GetModel(userModel.user_name, DTEnums.CodeEnum.RegVerify.ToString(), "d");
            if (codeModel == null)
            {
                codeModel = new Model.user_code();
                codeModel.user_id = userModel.id;
                codeModel.user_name = userModel.user_name;
                codeModel.type = DTEnums.CodeEnum.RegVerify.ToString();
                codeModel.str_code = strcode;
                codeModel.eff_time = DateTime.Now.AddDays(userConfig.regemailexpired);
                codeModel.add_time = DateTime.Now;
                new BLL.user_code().Add(codeModel);
            }
            //获得邮件内容
            Model.mail_template mailModel = new BLL.mail_template().GetModel("regverify");
            if (mailModel == null)
            {
                return "{\"status\":0, \"msg\":\"邮件发送失败，邮件模板内容不存在！\"}";
            }
            //替换模板内容
            string titletxt = mailModel.maill_title;
            string bodytxt = mailModel.content;
            titletxt = titletxt.Replace("{webname}", sysConfig.webname);
            titletxt = titletxt.Replace("{username}", userModel.user_name);
            bodytxt = bodytxt.Replace("{webname}", sysConfig.webname);
            bodytxt = bodytxt.Replace("{webtel}", sysConfig.webtel);
            bodytxt = bodytxt.Replace("{weburl}", sysConfig.weburl);
            bodytxt = bodytxt.Replace("{username}", userModel.user_name);
            bodytxt = bodytxt.Replace("{valid}", userConfig.regemailexpired.ToString());
            bodytxt = bodytxt.Replace("{linkurl}", "http://" + HttpContext.Current.Request.Url.Authority.ToLower()
                + new Web.UI.BasePage().getlink(sitepath, new Web.UI.BasePage().linkurl(0, "register", "?action=checkmail&code=" + codeModel.str_code)));
            //发送邮件
            try
            {
                DTMail.sendMail(sysConfig.emailsmtp, sysConfig.emailssl,
                    sysConfig.emailusername,
                    DESEncrypt.Decrypt(sysConfig.emailpassword, sysConfig.sysencryptstring),
                    sysConfig.emailnickname,
                    sysConfig.emailfrom,
                    userModel.email,
                    titletxt, bodytxt);
            }
            catch
            {
                return "{\"status\":0, \"msg\":\"邮件发送失败，请联系本站管理员！\"}";
            }
            return "success";
        }
        #endregion

        #endregion END通用方法===============================

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}